package com.anlu.base.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.anlu.base.admin.api.dto.UserInfo;
import com.anlu.base.admin.api.entity.SysUser;
import com.anlu.base.common.core.constant.CommonConstants;
import com.anlu.base.common.core.constant.SecurityConstants;
import com.anlu.base.common.core.util.R;
import com.anlu.base.common.core.util.RetOps;
import org.springframework.core.Ordered;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public interface PigUserDetailsService extends UserDetailsService, Ordered {

    default boolean support(String clientId,String grantType){
        return true;
    }

    @Override
    default int getOrder(){
        return 0;
    }

    /**
     * 构建userdetails
     * @param result 用户信息
     * @return UserDetails
     */
    default UserDetails getUserDetails(R<UserInfo> result){
        UserInfo info = RetOps.of(result).getData().orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        Set<String> dbAuthSet = new HashSet<>();
        if(ArrayUtil.isNotEmpty(info.getRoles())){
            //获取角色
            Arrays.stream(info.getRoles()).forEach(role -> dbAuthSet.add(SecurityConstants.ROLE + role));
            //获取资源
            dbAuthSet.addAll(Arrays.asList(info.getPermissions()));
        }

        Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(dbAuthSet.toArray(new String[0]));
        SysUser user = info.getSysUser();
        //构造security用户
        return new PigUser(user.getUserId(), user.getDeptId(), user.getUsername(),
                SecurityConstants.BCRYPT + user.getPassword(), user.getPhone(), true, true, true,
                StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), authorities);
    }

    default UserDetails loadUserByUser(PigUser pigUser){
        return this.loadUserByUsername(pigUser.getUsername());
    }
}
